use crate::api_error::ApiError;
use crate::context::AppContext;
use crate::json_helper::JsonHelper;
use axum::{
    extract::{Path, State},
    routing::get,
    Router,
};
use std::sync::Arc;
use tracing::info;

const DEFAULT_REMOTE_CRATES_INDEX_URL: &str = "https://api.crates-vsc.space";
const DEFAULT_PROXY_URL: &str = "socks5://127.0.0.1:1080";

pub(crate) fn api(ctx: Arc<AppContext>, _is_https: bool) -> Router {
    Router::new()
        .route("/crates-index/index/versions/:crate", get(crates_index))
        .with_state(ctx)
}

async fn crates_index(
    State(context): State<Arc<AppContext>>,
    Path(name): Path<String>,
) -> Result<String, ApiError> {
    let proxy = &context.config["config"]["proxy_url"];
    let proxy = proxy.str(DEFAULT_PROXY_URL);
    let proxy = reqwest::Proxy::all(proxy)?;
    let client = reqwest::Client::builder().proxy(proxy).build()?;
    let url = &context.config["config"]["remote_crates_index_url"];
    let url = url.str(DEFAULT_REMOTE_CRATES_INDEX_URL);
    let url = format!("{}/index/versions/{}", url, name);
    let res = client.get(url).send().await?;
    let text = res.text().await?;
    info!("name={},response={}", name, text);
    Ok(text)
}
